import autoDisposeWhenUnload from "./autoDisposeWhenUnload";

const instanceList = [];
const dataList = [];

autoDisposeWhenUnload(function () {
    instanceList.forEach(i => i?.destroy());
    instanceList.splice(0, instanceList.length);
    dataList.splice(0, dataList.length);
});

export default class SpecificLotteryRate {
    constructor(list, excludeGot = true) {
        list = list.filter(item => 0 < item.rate);
        instanceList.push(this);
        dataList.push({
            list: list.map(item => ({...item,})),
            total: list.reduce((res, item) => res + item.rate, 0),
            excludeGot,
        });
    }

    getOne() {
        const data = dataList[instanceList.indexOf(this)];
        const rand = data.total * Math.random();

        let start = 0;
        const res = data.list.find(item => start <= rand && rand < (start += item.rate));

        if (data.excludeGot) {
            const index = data.list.indexOf(res);
            data.list.splice(index, 1);
            data.total--;
        }

        return res.data;
    }
}
